import { useSetState, useUpdateEffect } from "ahooks";
import { Image, ScrollView, Text, View } from "@tarojs/components";

import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import ByIcon from "@/components/ui/ByIcon";
import ByCell from "@/components/ui/ByCell";
import Money from "@/components/app/Money";
import ByText from "@/components/ui/ByText";
import ByButton from "@/components/ui/ByButton";
import ByCounter from "@/components/ui/ByCounter";
import FormInput from "@/components/common/FormInput";
import ByPopupBottom from "@/components/ui/ByPopupBottom";
import TagRadioGroup from "@/components/app/TagRadioGroup";
import FormInputNumber from "@/components/common/FormInputNumber";
import { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";

import useFetch from "@/hooks/useFetch";
import ApiMaterial from "@/api/material";

import { MaterialDetail, MaterialDetailDTO } from "@/types/material";
import ByImage from "@/components/ui/ByImage";
import setting from "@/utils/setting";
import Taro from "@tarojs/taro";

type PopupProductDetailProps = {
  showPrice?: boolean;
  hiddenArea?: boolean;
  selected: MaterialDetailDTO;
  productId: number;

  /**
   * 用于设置对应的价格和名称
   */
  activeTab: {
    // 是否是套餐
    isPackage: boolean;
    priceName: string;
    priceValue: string;
  };
};
type PopupProductDetailEvent = {
  onConfirm: (event: MaterialDetailDTO) => void;
} & ByPopupBottomEvent;

const splitStrToOptions = (text?: string) => {
  if (text) {
    return text.split(",").map((e) => ({ label: e }));
  }

  return undefined;
};

export default ({
  productId,
  selected,
  activeTab,
  showPrice,
  hiddenArea,

  onCancel,
  onConfirm,
}: PopupProductDetailProps & PopupProductDetailEvent) => {
  // 获取材料详情
  const { data } = useFetch<MaterialDetail>(ApiMaterial.detail, {
    defaultParams: [{ materialId: productId }],
  });

  const [model, setModel] = useSetState({ ...selected });

  useUpdateEffect(() => {
    const { isPackage } = activeTab;

    if (data) {
      setModel({
        Spec: data.Spec,
        MaterialUnit: data.Unit,
        MaterialId: data.MaterialID,
        MatchCode: data.MaterialCode,

        brandCategory: data.BrandCategory,
        materialBrand: data.MaterialBrand,
        materialPicture: data.MaterialPicture,
        materialClassName: data.MaterialClassName,

        BuyPrice: data.BuyPrice,
        ContractPrice: data.ContractPrice,
        UsePriceName: activeTab.priceValue,
        MaterialPrice: isPackage ? 0 : data[activeTab.priceValue] || 0,
        MaterialName: `${data?.MaterialName}(${activeTab.priceName})`,
      });
    }
  }, [data]);

  //  总价
  const total = (model.Num || 0) * model.MaterialPrice;

  // 颜色列表
  const colors = splitStrToOptions(data?.Color);
  const standards = splitStrToOptions(data?.Standard);

  const handleConfirm = () => {
    let { Color, Standard } = model;

    Color = Color ? `[颜色：${Color}]` : "";
    Standard = Standard ? `[型材：${Standard}]` : "";

    onConfirm({
      ...model,
      Remark: model.Remark + Color + Standard,
    });
  };

  // 是否是销售价
  const isSalePrice = "SalePrice" == activeTab.priceValue;


  // 图片地址
  const imageUrl = data?.MaterialPicture ? setting.host + data.MaterialPicture : ""

  return (
    <ByPopupBottom
      title={data?.MaterialName}
      slotFooter={
        <ByRow
          content="between"
          align="center"
          className="border-t-1 border-line-light p-3"
        >
          <ByCol span={"auto"} className="text-third text-sm">
            总计：
            <Money value={total} />
          </ByCol>

          <ByButton onClick={handleConfirm}>添加至选材单</ByButton>
        </ByRow>
      }
      style={{ zIndex: 200 }}
      onCancel={onCancel}
    >
      <ScrollView scroll-y className="h-[66vh]">
        <View className="flex-center bg-page rounded-md min-h-[220px] mx-3 mb-3">
          {
            imageUrl ?
              <Image src={imageUrl} className="w-full h-[600px]" mode="aspectFit"
                onClick={() => Taro.previewImage({ current: imageUrl, urls: [imageUrl] })}
              /> :
              <ByIcon name="NoImg" size={86} />
          }
        </View>

        <View className="px-4 text-third text-sm">
          <Text>{data?.brandCategory}</Text>
          <Text className="pl-1">
            {data?.Spec}({data?.Unit})
          </Text>
          <Text className="pl-1">{data?.Remark}</Text>
        </View>

        <View className="mt-3 px-4">
          {!hiddenArea && (
            <ByCell requierd label="所属区域" vertical>
              <FormInput value={model.Area} disabled />
            </ByCell>
          )}

          <ByCell requierd label="材料名称" vertical>
            <FormInput value={model.MaterialName} disabled={!data?.IsCanEdit} onChange={e => setModel({ MaterialName: e })} />
          </ByCell>

          <ByCell requierd label="材料价格" vertical>
            <FormInputNumber
              prefix="¥"
              disabled={!data?.IsCanEdit}
              value={model.MaterialPrice}
              onChange={(e) => setModel({ MaterialPrice: e })}
              placeholder="输入价格"
              precision={2}
            />
          </ByCell>

          {showPrice && (
            <View className="bg-page rounded-md p-2 text-center">
              <ByRow content="between">
                <View>
                  <ByText size="sm">
                    ¥{data?.BuyPrice ?? "**"}/{data?.Unit}
                  </ByText>
                  <ByText size="xs" block className="mt-1">
                    采购价
                  </ByText>
                </View>

                <View>
                  <ByText size="sm">
                    ¥{data?.ContractPrice ?? "**"}/{data?.Unit}
                  </ByText>
                  <ByText size="xs" block className="mt-1">
                    承包价
                  </ByText>
                </View>

                <View>
                  <ByText size="sm">
                    ¥{data?.SalePrice ?? "**"}/{data?.Unit}
                  </ByText>
                  <ByText size="xs" block className="mt-1">
                    销售价
                  </ByText>
                </View>
              </ByRow>
            </View>
          )}

          {!showPrice && (
            <ByRow>
              <ByCol span={6}>
                <ByCell requierd label="价格类型" vertical>
                  {activeTab.priceName}
                </ByCell>
              </ByCol>

              {!isSalePrice && (
                <ByCol span={6}>
                  <ByCell requierd label="升级价" vertical>
                    <ByText type="second">+</ByText>
                    <Money value={model.MaterialPrice} />
                    {model.MaterialUnit && (
                      <ByText size="sm" type="second">
                        /{model.MaterialUnit}
                      </ByText>
                    )}
                  </ByCell>
                </ByCol>
              )}
            </ByRow>
          )}

          {colors && (
            <ByCell label="颜色" vertical>
              <TagRadioGroup
                options={colors}
                value={[model.Color]}
                onChange={([e]) => setModel({ Color: e })}
              />
            </ByCell>
          )}

          {standards && (
            <ByCell label="型材" vertical>
              <TagRadioGroup
                options={standards}
                value={[model.Standard]}
                onChange={([e]) => setModel({ Standard: e })}
              />
            </ByCell>
          )}

          <ByCell requierd label="材料数量" vertical>
            <ByCounter
              min={0}
              precision={2}
              value={model.Num}
              className="w-[240px]"
              onChange={(e) => setModel({ Num: e })}
            />
          </ByCell>

          <ByCell label="选材备注" vertical>
            <FormInput
              type="textarea"
              placeholder="输入选材备注"
              value={model.Remark}
              onChange={(e) => setModel({ Remark: e })}
            />
          </ByCell>
        </View>
      </ScrollView>
    </ByPopupBottom>
  );
};
